﻿using SqlSugar;
using XJay.Identity.IService;
using XJay.Identity.Model.User.Export;
using XJay.Identity.Model.User.Import;
using Microsoft.Extensions.Configuration;
using XJay.Identity.Common.CustomException;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using System.Security.Claims;
using System.IdentityModel.Tokens.Jwt;
using XJay.DB.Model;

namespace XJay.Identity.Service
{
    public class UserServer : IUserServer
    {
        private readonly IConfiguration _configuration;
        private readonly ISqlSugarClient _sqlSugarClient;
        public UserServer(IConfiguration configuration, ISqlSugarClient sqlSugarClient)
        {
            _configuration = configuration;
            _sqlSugarClient = sqlSugarClient;
        }
        public async Task<UserDto> LoginAsync(LoginParam param)
        {
            //var user = await _sqlSugarClient.Queryable<User>().Where(p => p.Email == param.Mail && p.Pwd == param.PassWord).FirstAsync();
            var user = new User() { 
                Email = "string",
                UserName = "string",
                UID = 1
            };
            if (user == null)
            {
                throw new XJayException("账号或者密码错误");
            }
            //查找角色
            var role = 1/*await _sqlSugarClient.Queryable<Permission>().Where(p => p.UID == user.UID).Select(p => p.RID).FirstAsync()*/;

            // 2. 从 appsettings.json 中读取SecretKey
            var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:SecretKey"]));

            // 3. 选择加密算法
            var algorithm = SecurityAlgorithms.HmacSha256;

            // 4. 生成Credentials
            var signingCredentials = new SigningCredentials(secretKey, algorithm);

            // 5. 从 appsettings.json 中读取Expires
            var expires = Convert.ToInt32(_configuration["JWT:Expires"]);


            Claim[] claims = new[] {
                            new Claim("UID", user.UID.ToString()),
                            new Claim("UserName", user.UserName),
                            new Claim("Role", role.ToString()),
                            new Claim("Email", user.Email)
                        };

            // 6. 根据以上，生成token
            var token = new JwtSecurityToken(
                _configuration["JWT:Issuer"],     //Issuer
                _configuration["JWT:Audience"],   //Audience
                claims,                          //Claims,
                DateTime.Now,                    //notBefore
                DateTime.Now.AddMinutes(expires),   //expires
                signingCredentials               //Credentials
            );

            // 7. 将token变为string
            var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);

            return new UserDto()
            {
                UID = user.UID,
                UserName = user.UserName,
                Role = role,
                Token = jwtToken,
                Expiration = expires.ToString()
            };
        }


    }
}